package com.example.intelglasses;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedHashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.intelglasses.MainActivity;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.example.intelglasses.JsonParser;
import com.iflytek.sunflower.FlowerCollector;

public class generator extends Activity implements OnClickListener {
	private ImageButton buttjuchiButton;
	private ImageButton buttfangboButton;
	private ImageButton buttsinButton;
	private Button buttchangeButton;
	private Button buttchangeData;
	private Vibrator vibrator;
	private EditText editjuchiFu;
	private EditText editjuchiFre;
	private TextView textSignalStatus;
	private Button signalbutt;

	private TextView recvText;
	private TextView statusText;
	static char buffertemp;
	char[] buffer1;
	public boolean ispress = false;
	public Thread mThreadClient = null;
	public Socket mSocketClient = null;
	static BufferedReader mBufferedReaderServer = null;
	static PrintWriter mPrintWriterServer = null;
	static BufferedReader mBufferedReaderClient = null;
	static PrintWriter mPrintWriterClient = null;
	private String recvMessageClient = "";
	private String ipstring, portstring;

	// 语音听写对象
	private SpeechRecognizer mIat;
	// 语音听写UI
	private RecognizerDialog mIatDialog;
	// 用HashMap存储听写结果
	private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
	private EditText mResultText;
	private Toast mToast;
	// 引擎类型
	private String mEngineType = SpeechConstant.TYPE_CLOUD;
	private ImageButton buttvoiceButton;
	// printResult会发神经执行2次,所以立下flag砍掉1次
	private boolean firstFlag = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		this.setContentView(R.layout.change_main);
		buttchangeButton = (Button) findViewById(R.id.buttt1);
		buttchangeData = (Button) findViewById(R.id.buttt2);
		buttfangboButton = (ImageButton) findViewById(R.id.buttfangbo);
		buttjuchiButton = (ImageButton) findViewById(R.id.buttjuchi);
		buttsinButton = (ImageButton) findViewById(R.id.buttsin);
		signalbutt = (Button) findViewById(R.id.buttsignalOpenClose);
		statusText = (TextView) findViewById(R.id.textStatuschange);
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		textSignalStatus = (TextView) findViewById(R.id.textSignalchange);

		editjuchiFu = (EditText) findViewById(R.id.editTextjuchiFuzhi);
		editjuchiFre = (EditText) findViewById(R.id.editTextjuchipin);

		buttvoiceButton = (ImageButton) findViewById(R.id.buttvoicesignal);
		// 初始化识别对象
		mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
		// 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
		mIatDialog = new RecognizerDialog(generator.this, mInitListener);
		mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
		mResultText = ((EditText) findViewById(R.id.iat_text));
		mEngineType = SpeechConstant.TYPE_CLOUD;

		mThreadClient = new Thread(mRunnable); // new出一个wifi线程
		mThreadClient.start(); // 开启线程
	}

	/**
	 * 初始化监听器。
	 */
	private InitListener mInitListener = new InitListener() {

		@Override
		public void onInit(int code) {
			if (code != ErrorCode.SUCCESS) {
				showTip("初始化失败，错误码：" + code);
			}
		}
	};
	/**
	 * 听写监听器。
	 */
	private RecognizerListener recognizerListener = new RecognizerListener() {

		@Override
		public void onBeginOfSpeech() {
			showTip("开始说话");
		}

		@Override
		public void onError(SpeechError error) {
			// Tips：
			// 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
			// 如果使用本地功能（语音+）需要提示用户开启语音+的录音权限。
			showTip(error.getPlainDescription(true));
		}

		@Override
		public void onEndOfSpeech() {
			showTip("结束说话");
		}

		@Override
		public void onResult(RecognizerResult results, boolean isLast) {
			// printResult(results);

			if (isLast) {
			}
		}

		@Override
		public void onVolumeChanged(int volume) {
			showTip("当前正在说话，音量大小：" + volume);
		}

		@Override
		public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
		}
	};

	private void printResult(RecognizerResult results) {
		if (firstFlag == true) {
			firstFlag = false;
			String text = JsonParser.parseIatResult(results.getResultString());
			String sn = null;
			// 读取json结果中的sn字段
			try {
				JSONObject resultJson = new JSONObject(
						results.getResultString());
				sn = resultJson.optString("sn");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			mIatResults.put(sn, text);

			StringBuffer resultBuffer = new StringBuffer();
			for (String key : mIatResults.keySet()) {
				resultBuffer.append(mIatResults.get(key));
			}
			String tempResult = resultBuffer.toString();
			mResultText.append(resultBuffer.toString());
			// mResultText.setSelection(mResultText.length());
			switch (JudgeVoice.returnSignal(resultBuffer.toString())) {
			case 1:
				buttchangeButton.performClick();
				break;
			case 2:
				buttchangeData.performClick();
				break;
			case 3:
				signalbutt.performClick();
				break;
			case 4:
				buttjuchiButton.performClick();
				break;
			case 5:
				buttfangboButton.performClick();
				break;
			case 6:
				buttsinButton.performClick();
				break;
			case 11:
				this.finish();
				break;
			case 0:
				Toast.makeText(generator.this, "识别不出来呀~~~", Toast.LENGTH_LONG)
						.show();
				break;
			default:
				break;
			}
		} else {
			firstFlag = true;
		}

	}

	/**
	 * 听写UI监听器
	 */
	private RecognizerDialogListener recognizerDialogListener = new RecognizerDialogListener() {
		public void onResult(RecognizerResult results, boolean isLast) {
			printResult(results);
		}

		/**
		 * 识别回调错误.
		 */
		public void onError(SpeechError error) {
			showTip(error.getPlainDescription(true));
		}

	};

	private void showTip(final String str) {
		mToast.setText(str);
		mToast.show();
	}

	/**
	 * 参数设置
	 * 
	 * @param param
	 * @return
	 */
	public void setParam() {
		// 清空参数
		mIat.setParameter(SpeechConstant.PARAMS, null);

		// 设置听写引擎
		mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
		// 设置返回结果格式
		mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");
		String lag = "zh_cn";
		if (lag.equals("en_us")) {
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
		} else {
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
			// 设置语言区域
			mIat.setParameter(SpeechConstant.ACCENT, lag);
		}
		// 设置语音前端点
		mIat.setParameter(SpeechConstant.VAD_BOS, "4000");
		// 设置语音后端点
		mIat.setParameter(SpeechConstant.VAD_EOS, "1000");
		// 设置标点符号
		mIat.setParameter(SpeechConstant.ASR_PTT, "0");
		// 设置音频保存路径
		mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH,
				Environment.getExternalStorageDirectory()
						+ "/iflytek/wavaudio.pcm");
		// 设置听写结果是否结果动态修正，为“1”则在听写过程中动态递增地返回结果，否则只在听写结束之后返回最终结果
		// 注：该参数暂时只对在线听写有效
		mIat.setParameter(SpeechConstant.ASR_DWA, "0");
	}

	@Override
	protected void onResume() {
		// 移动数据统计分析
		FlowerCollector.onResume(generator.this);
		super.onResume();
	}

	@Override
	protected void onPause() {
		// 移动数据统计分析
		FlowerCollector.onPause(generator.this);
		super.onPause();
	}

	private Runnable mRunnable = new Runnable() {
		public void run() {

			try {
				Intent intent = getIntent();
				ipstring = intent.getStringExtra("ipstring");
				portstring = intent.getStringExtra("portint");
				mSocketClient = new Socket(intent.getStringExtra("ipstring"),
						Integer.valueOf(intent.getStringExtra("portint"))); // Port_num
				mBufferedReaderClient = new BufferedReader(
						new InputStreamReader(mSocketClient.getInputStream()));
				// 绑定输入流
				mPrintWriterClient = new PrintWriter(
						mSocketClient.getOutputStream(), true);
				recvMessageClient = "已连接成功!";// 消息
				vibrator.vibrate(50);
				Message msg = new Message();
				msg.what = 1;
				mHandler.sendMessage(msg);
			} catch (Exception e) {
				recvMessageClient = "IP 错误!!";// 消息
				Message msg = new Message();
				msg.what = 1;
				mHandler.sendMessage(msg);
				return;
			}
			buffer1 = new char[3];
			while (true) {
				try {
					mBufferedReaderClient.read(buffer1);
					buffertemp = buffer1[0];
					if (buffer1[0] == '$') {
						Message msg = new Message();
						msg.what = 2;
						mHandler.sendMessage(msg);
					}
					if (buffer1[0] == '^') {
						Message msg = new Message();
						msg.what = 3;
						mHandler.sendMessage(msg);
					}
				} catch (IOException e) {
				}

			}
		}
	};
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 0) {
			} else if (msg.what == 1) {
				if (recvMessageClient == "IP为空!!!"
						|| recvMessageClient == "IP 错误!!") {
					vibrator.vibrate(500);
				} else if (recvMessageClient == "已连接成功!") {
				}
				statusText.setText(recvMessageClient); // 刷新消息
			} else if (msg.what == 2) { // 2表示收到'1'
				buttvoiceButton.performClick();
			}
		}
	};
	int ret = 0;

	/** 语音开始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
	public void voiceActriveSignal(View source) {
		mResultText.setText(null);// 清空显示内容
		mIatResults.clear();
		setParam();
		boolean isShowDialog = true;
		if (isShowDialog) {
			// 显示听写对话框
			mIatDialog.setListener(recognizerDialogListener);
			mIatDialog.show();
			showTip(getString(R.string.text_begin));
		} else {
			// 不显示听写对话框
			mIatDialog.setListener(recognizerDialogListener);
			ret = mIat.startListening(recognizerListener);
			if (ret != ErrorCode.SUCCESS) {
				showTip("听写失败,错误码：" + ret);
			} else {
				showTip(getString(R.string.text_begin));
			}
		}
	}

	/** 底下按钮: 切回示波器act */
	public void changeToOSC(View source) {
		Intent intent = new Intent();
		intent.putExtra("ipstring", ipstring);
		intent.putExtra("portint", portstring);
		intent.setClass(generator.this, MainActivity.class);
		startActivity(intent);
		generator.this.finish();
	}

	/** 底下按钮: 切到数据查询界面act */
	public void changeToData(View source) {
		Intent intent = new Intent();
		intent.setClass(generator.this, QueryData.class);
		startActivity(intent);
		generator.this.finish();
	}

	/** 方波按钮 */
	public void onclickfangbo(View source) {
		vibrator.vibrate(20);
		try {
			if (Integer.valueOf(editjuchiFre.getText().toString()) >= 1
					&& Integer.valueOf(editjuchiFre.getText().toString()) <= 1000) {
				String tempflushFreStringfang = String.valueOf((Integer
						.valueOf(editjuchiFre.getText().toString()) - 1));
				String tempstringString = editjuchiFu.getText().toString()
						.substring(0, 1)
						+ editjuchiFu.getText().toString().substring(2);
				mPrintWriterClient.print("&f^");
				mPrintWriterClient.flush(); // 发送缓冲区的东西
				mPrintWriterClient.print("&A0" + tempstringString + "^");
				mPrintWriterClient.flush(); // 发送缓冲区的东西
				mPrintWriterClient.print("&F" + tempflushFreStringfang + "^");
				mPrintWriterClient.flush(); // 发送缓冲区的东西
				textSignalStatus.setText("方波");
			} else {
				Toast.makeText(generator.this, "频率设置需为:1~1000",
						Toast.LENGTH_LONG).show();
			}
		} catch (Exception e) {
			Toast.makeText(generator.this, "请到示波器界面进行连接", Toast.LENGTH_LONG)
					.show();
		}
	}

	/** sin按钮 */
	public void onclicksin(View source) {
		vibrator.vibrate(20);
		try {
			//输入框为1位时,发送时自动补2个0;
			//输入框为2位时,发送时自动补1个0;
			if (Integer.valueOf(editjuchiFre.getText().toString()) >= 1
					&& Integer.valueOf(editjuchiFre.getText().toString()) <= 1000) {
				String tempflushFreStringsin = String.valueOf((Integer
						.valueOf(editjuchiFre.getText().toString()) - 1));
				String tempstringString = editjuchiFu.getText().toString()
						.substring(0, 1)
						+ editjuchiFu.getText().toString().substring(2);
				mPrintWriterClient.print("&s^");
				mPrintWriterClient.flush(); // 发送缓冲区的东西
				mPrintWriterClient.print("&A0" + tempstringString + "^");
				mPrintWriterClient.flush(); // 发送缓冲区的东西
				if(Integer.valueOf(tempflushFreStringsin)>=100)
				{
				mPrintWriterClient.print("&F" + tempflushFreStringsin + "^");
				}else if(Integer.valueOf(tempflushFreStringsin)>=10)
				{
					mPrintWriterClient.print("&F0" + tempflushFreStringsin + "^");
				}
				else {
					mPrintWriterClient.print("&F00" + tempflushFreStringsin + "^");
				}
				mPrintWriterClient.flush(); // 发送缓冲区的东西
				textSignalStatus.setText("正弦波");
			} else {
				Toast.makeText(generator.this, "频率设置需为:1~1000",
						Toast.LENGTH_LONG).show();
			}
		} catch (Exception e) {
			Toast.makeText(generator.this, "请到示波器界面进行连接", Toast.LENGTH_LONG)
					.show();
		}
	}

	/** 锯齿按钮 */
	public void onclickjuchi(View source) {
		vibrator.vibrate(20);
		try {
			if (Integer.valueOf(editjuchiFre.getText().toString()) >= 1
					&& Integer.valueOf(editjuchiFre.getText().toString()) <= 1000) {
				String tempflushFreStringju = String.valueOf((Integer
						.valueOf(editjuchiFre.getText().toString()) - 1));
				String tempstringString = editjuchiFu.getText().toString()
						.substring(0, 1)
						+ editjuchiFu.getText().toString().substring(2);
				mPrintWriterClient.print("&j^");
				mPrintWriterClient.flush(); // 发送缓冲区的东西
				mPrintWriterClient.print("&A0" + tempstringString + "^");
				mPrintWriterClient.flush(); // 发送缓冲区的东西
				mPrintWriterClient.print("&F" + tempflushFreStringju + "^");
				mPrintWriterClient.flush(); // 发送缓冲区的东西
				textSignalStatus.setText("锯齿波");
			} else {
				Toast.makeText(generator.this, "频率设置需为:1~1000",
						Toast.LENGTH_LONG).show();
			}
		} catch (Exception e) {
			Toast.makeText(generator.this, "请到示波器界面进行连接", Toast.LENGTH_LONG)
					.show();
		}
	}

	/** 信号发生器的开启 */
	public void signalOpenClose(View source) {
		vibrator.vibrate(20);
		if (ispress == false) {
			try {
				mPrintWriterClient.print("&o^");
				mPrintWriterClient.flush(); // 发送缓冲区的东西
				textSignalStatus.setText("已开启");
				signalbutt.setText("关闭信号发生器");
				ispress = true;
			} catch (Exception e) {
				Toast.makeText(generator.this, "请到示波器界面进行连接", Toast.LENGTH_LONG)
						.show();
			}
		} else if (ispress == true) {
			try {
				mPrintWriterClient.print("&O^");
				mPrintWriterClient.flush(); // 发送缓冲区的东西
				textSignalStatus.setText("已关闭");
				signalbutt.setText("开启信号发生器");
				ispress = false;
			} catch (Exception e) {
				Toast.makeText(generator.this, "请到示波器界面进行连接", Toast.LENGTH_LONG)
						.show();
			}
		}

	}

	public void onDestroy() {
		super.onDestroy();
		try {
			if (mSocketClient != null) {
				mSocketClient.close();
				mSocketClient = null;
				mPrintWriterClient.close();
				mPrintWriterClient = null;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		mThreadClient.interrupt();
	}

	@Override
	public void onClick(View v) {

	}
}
